#include "wxFemViewerApp.h"
#include "AppImpl.hpp"
#include "wxMainWindow.h"
#include "wxApproxModWnd.h"
#include "wx/config.h"
#include "wx/app.h"
#include "../inc/WindowFV.h"
#include "../inc/GraphicsSettings.h"
#include "../inc/ModelControler.h"
#include "ViewManager.h"
#include "../../utils/fv_exception.h"
#ifdef _USE_FV_IO_MGR
#include "../../include/IOManager.h"
#endif

#ifdef _USE_FV_EXT_MOD
#include "../../include/ApproxModule.h"
#endif

#include "fv_compiler.h"
#include "fv_config.h"
#include "fv_txt_utls.h"
#include "Log.h"
#include "dbg.h"
#include<wx/log.h>

#include<ostream>

namespace FemViewer {
namespace WxGUI		{
	
IMPLEMENT_APP_NO_MAIN(wxFemViewerApp)

Core<wxFemViewerApp *>* wxFemViewerApp::_parent = nullptr;

wxFemViewerApp * wxFemViewerApp::GetInstnace()
{
	if (IsInit()) return static_cast<wxFemViewerApp*>(wxApp::GetInstance());
	return NULL;
}

int wxFemViewerApp::Init(int argc,char **argv,Core<WxGUI::wxFemViewerApp *> *core)
{
	_parent = core;
	// becauseof some early GL operation
	if( !glutGet( GLUT_INIT_STATE ) )
		glutInit( &argc,argv );
	FV_CHECK_ERROR_GL();
	//ModelCtrlInst().Do(ModelCtrl::INIT);
    //return 0;
	//mfp_debug("po inicjacji gluta2\n");
	argc = 1; // ignore options, only program name
	return wxEntry(argc, (wxChar**)argv);
}


int wxFemViewerApp::Init2(int argc,char **argv)
{
	mfp_debug("wxFemViewer::Init2\n");
	if( !glutGet( GLUT_INIT_STATE ) )
		glutInit( &argc,argv );

	ModelCtrlInst().Do(ModelCtrl::INIT);
	return 0;
}

bool wxFemViewerApp::IsInit()
{
	return !!(wxApp::GetInstance() != NULL);
}

void wxFemViewerApp::ShutDown()
{
	//logd(("wxFemViewerApp::ShutDown\n"));
	wxGetApp().m_pWnd->m_shutdown = true;
}

wxFemViewerApp::wxFemViewerApp() : m_pWnd(0)
{
	logd("Constructor wxFemViewerApp\n");
}

wxFemViewerApp::~wxFemViewerApp(void)
{
	logd("Destructor wxFemViewerApp\n");
	//if(m_pWnd != NULL)
	//{
	//	delete m_pWnd;
	//	m_pWnd = NULL;
	//}

	//delete wxConfigBase::Set((wxConfigBase*) NULL);
}

bool wxFemViewerApp::OnInit()
{
	mfp_debug("OnInit: wxFVApp: starting application\n");

	if (! wxApp::OnInit())
		return false;
	
	// First: set application & vendor name for wxConfig
	SetVendorName(wxT(MOD_FEM_VIEWER_NAME));
	SetAppName(wxT("FemViewer"));
	m_pWnd = new wxMainWindow( 100,100,imageWidth,imageHeight,wxT("FemViewer"));
	wxASSERT( m_pWnd != nullptr );

	m_pWnd->DoInit();
	m_pWnd->Refresh();
	m_pWnd->Show(true);

#if wxUSE_IMAGE
    wxInitAllImageHandlers();
#endif

    SetTopWindow( m_pWnd );

	return true;
}

int wxFemViewerApp::OnExit()
{
    mfp_debug("OnExit: wxFVApp: exiting application.\n");

    if ( wxTheApp ) wxEntryCleanup();
	// Returns
	return wxApp::OnExit();
}

}// end namespace WxGUI
}// end namespace FemViewer


